﻿using BTNode = GX.BTTree.BTNode;
using BTNodeContainer = GX.BTTree.BTNodeContainer;
namespace GX
{
    /**选择一个满足条件的执行：没有则失败
    */
    public class BTNodeSequence : BTNodeContainer
    {
        int _numTotal;
        int _numSkip;
        int _numDone;
        int _numSuccess;
        protected override void OnEnter(bool isRestart)
        {
            _numTotal = this.numChildren;
            _numSkip = 0;
            _numDone = 0;
            _numSuccess = 0;

            StartNext();
        }
        void StartNext()
        {
            if(_numSuccess != _numDone)
            {
                Fail();
                return ;
            }
            while(_numDone +_numSkip < _numTotal)
            {
                var node = this.GetChildAt(_numDone + _numSkip);
                if(node.Evaluate())
                {
                    node.Start(this.OnChildDone);
                    break;
                }else
                {
                    ++ _numSkip;
                }
            }

            if(_numDone + _numSkip == _numTotal)
                Finish();
        }
        protected override void OnExit()
        {
            if (this.isInterrupt)
            {
                this.GetChildAt(_numDone).Stop();
            }
        }
        override protected void OnChildDone(BTNode node)
        {
            if (this.isDone) return;

            ++_numDone;

            if (node.isSuccess)
            {
                ++ _numSuccess;
            }

            StartNext();
        }

    }
}
;